package net.huashitong.synthetical.ctrl;

import com.alibaba.fastjson.JSONArray;
import com.sirdc.modules.core.config.Global;
import com.sirdc.modules.core.web.JsonBaseController;
import com.sirdc.modules.core.web.model.Message;
import com.sirdc.modules.sys.entity.SysFile;
import com.sirdc.modules.sys.service.RedisService;
import com.sirdc.modules.sys.service.SysFileService;
import com.sirdc.modules.utils.StringUtils;
import net.huashitong.util.UtilsTools;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.util.UriUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Controller
@RequestMapping("/filesUpload")
public class CommCtrl extends JsonBaseController {

    public static String  DCURL="http://120.78.158.120:8002/";
    public static String  DCURL1="http://120.78.158.120:8077/";
    @Autowired
    private SysFileService fileservice;

    @Autowired
    private RedisService redisService;


    @Override
    protected String getView(String s) {
        return null;
    }

    @RequestMapping
    public String upload(String s){
        return getView("/modules/task/"+s);
    }

    //文件上传
    @ResponseBody
    @RequestMapping("/uploadBatch")
    public String uplaodfile(@RequestParam MultipartFile files, MultipartHttpServletRequest request) {
        String str = null;
        Message msg = new Message();
        if (files == null) {
            msg.setCode(UtilsTools.ERROR);
            return null;
        }
        //System.out.println(projectStage);
        try {
            SysFile sysfile = new SysFile();
                fileservice.saveFile(sysfile, files);
                Map<String, Object> mao = new HashMap<String, Object>();
                mao.put("sysid", sysfile.getSysId());
                mao.put("oldName", sysfile.getOldName());
            //filesave.fileSave(sysfile, files);

//			str = "code:'200',data:{'sysid':"+sysfile.getSysId()+"}";

            msg.setCode(UtilsTools.CODE);
            msg.setData(mao);
            str = JSONArray.toJSONString(msg);


        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return str;
    }


    //多文件上传
    @ResponseBody
    @RequestMapping("/uploadFiles")
    public String uplaodfiles(@RequestParam MultipartFile[] files, MultipartHttpServletRequest request) {
        String str = null;
        List<MultipartFile> file1 = request.getMultiFileMap().get("file");
        Message msg = new Message();
        if (files == null) {
            msg.setCode(UtilsTools.ERROR);
            return null;
        }
        //System.out.println(projectStage);
        try {
            List<Map<String,Object>>mapList=new ArrayList<>();

            SysFile sysfile = new SysFile();
            for (MultipartFile file : file1) {
                fileservice.saveFile(sysfile, file);
                Map<String, Object> mao = new HashMap<String, Object>();
                mao.put("sysid", sysfile.getSysId());
                mao.put("oldName", sysfile.getOldName());
                mapList.add(mao);
            }
            //filesave.fileSave(sysfile, files);

//			str = "code:'200',data:{'sysid':"+sysfile.getSysId()+"}";

            msg.setCode(UtilsTools.CODE);
            msg.setData(mapList);
            str = JSONArray.toJSONString(msg);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return str;
    }

    @ResponseBody
    @RequestMapping("/appUploadFiles")
    public String appUploadFiles(@RequestParam MultipartFile[] files, MultipartHttpServletRequest request) {
        String str = null;
        List<MultipartFile> file1 = request.getMultiFileMap().get("file");
        Message msg = new Message();
        if (files == null) {
            msg.setCode(UtilsTools.ERROR);
            return null;
        }
        //System.out.println(projectStage);
        try {
            List<Map<String,Object>>mapList=new ArrayList<>();

            SysFile sysfile = new SysFile();
            for (MultipartFile file : file1) {
                fileservice.saveFile(sysfile, file);
                Map<String, Object> mao = new HashMap<String, Object>();
                mao.put("sysid", sysfile.getSysId());
                mao.put("oldName", sysfile.getOldName());
                mapList.add(mao);
            }
            //filesave.fileSave(sysfile, files);

//			str = "code:'200',data:{'sysid':"+sysfile.getSysId()+"}";

            msg.setCode(UtilsTools.CODE);
            msg.setMessage(UtilsTools.CODE);
            msg.setData(mapList);
            str = JSONArray.toJSONString(msg);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            msg.setCode(UtilsTools.ERROR);
            msg.setMessage(UtilsTools.ERROR);
            str = JSONArray.toJSONString(msg);
        }
        return str;
    }


    //文件下载
    @RequestMapping(value = "/download")
    public void downLoad(String id, HttpServletRequest req, HttpServletResponse resp,String name) throws Exception {
        downLoadFileId(id, req, resp,name);
    }

    /**
     * 返回文件路径
     * @param id
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/fileURL")
    public Message fileURL(String id,HttpServletRequest req, HttpServletResponse resp){
        if (StringUtils.isBlank(id)){
            logger.error("500","请求的文件不存在" );
            return coverMessage("500","文件不存在");
        }
        SysFile sysFile = fileservice.getById(id);
        String filepath = sysFile.getUrl();
        String name = sysFile.getOldName();
        int index = filepath.lastIndexOf(Global.USER_DIR);
        if (index >= 0) {
            filepath = filepath.substring(index + Global.USER_DIR.length());
        }
        try {
//            filepath =DCURL+Global.getUploadBaseDir()+ UriUtils.decode(filepath, "UTF-8");
            filepath =DCURL1+Global.getUploadBaseDir()+ UriUtils.decode(filepath, "UTF-8");
        } catch (Exception e1) {
            // TODO Auto-generated catch block
            logger.error(String.format("解释文件路径失败，URL地址为%s", filepath), e1);
        }
        Map<String,String>map=new HashMap<>();
        map.put("filepath",filepath );
        map.put("name",name );
        return coverMessage("200","success",map);
    }

    public void downLoadFileId(String fileId, HttpServletRequest req, HttpServletResponse resp, String name) throws Exception {
        if (StringUtils.isBlank(fileId)){
            logger.error("请求的文件不存在");
        }
        SysFile sysFile = fileservice.getById(fileId);
        if (StringUtils.isNotBlank(sysFile.getOldName())){
            name=sysFile.getOldName();
        }
        if (StringUtils.isBlank(name)){
            name=sysFile.getFilename()+"."+sysFile.getFileType();
        }
        String encode = URLEncoder.encode(name, "UTF-8");
        if (sysFile == null) {
            throw new Exception(" current request path is empty");
        }
        String filepath = sysFile.getUrl();
        int index = filepath.lastIndexOf(Global.USER_DIR);
        if (index >= 0) {
            filepath = filepath.substring(index + Global.USER_DIR.length());

        }
        try {
            filepath = UriUtils.decode(filepath, "UTF-8");
        } catch (Exception e1) {
            // TODO Auto-generated catch block
            logger.error(String.format("解释文件路径失败，URL地址为%s", filepath), e1);
        }
        File file = new File(Global.getUploadBaseDir() + filepath);
        resp.reset();
        InputStream inputStream = new FileInputStream(file);
        try {


            resp.setHeader("Content-Type", "application/x-download");
            resp.setHeader("Content-Disposition", "attachment; filename=" + encode);
            FileCopyUtils.copy(inputStream, resp.getOutputStream());


            return;
        } catch (Exception e) {
            // TODO Auto-generated catch block
            throw new FileNotFoundException("请求的文件不存在");
        }


    }

    @RequestMapping(value = "/createhead", method = RequestMethod.GET)
    public String showAddView(Model model) {

        Map<String, String> map = new HashMap<>();

        redisService.set("taskName", "任务名称");
        redisService.set("aaa001", "任务状态");
        redisService.set("resDept", "承办单位");
        redisService.set("resUser", "责任人");
        redisService.set("taskResult", "是否及时办结");
        redisService.set("supervisionScore", "督查组绩效得分");
        redisService.set("respScore", "责任单位绩效得分");
        redisService.set("sysId", "任务单号");
        redisService.set("startDate", "开始日期");
        redisService.set("endDate", "结束日期");
        redisService.set("planStartDate", "计划开始时间");
        redisService.set("planEndDate", "计划结束时间");
        redisService.set("expirationDate", "到期日期");
        redisService.set("taskContent", "任务内容");
        redisService.set("resDept", "责任单位");
        redisService.set("resPhone", "责任人手机号");
        redisService.set("operatorUser", "经办人");
        redisService.set("operatorPhone", "经办人手机号");
        redisService.set("taskDate", "任务时间");
        redisService.set("groupCode", "督查组类别");
        redisService.set("phones", "督查组类别");
        /* redisService.set("headCode",map);*/
        //redisService.

       /* System.out.println("----------");
        System.out.println(redisService.get("headCode"));*/


        return "ok";
    }

    /**
     * pdf预览
     * @param fileId
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/lookPDF",method = RequestMethod.POST)
    public Message lookPDF(String fileId) {
        SysFile sysFile = fileservice.getById(fileId);
        String filepath = sysFile.getUrl();
        int index = filepath.lastIndexOf(Global.USER_DIR);
        if (index >= 0) {
            filepath = filepath.substring(index + Global.USER_DIR.length());

        }
        try {
            filepath = UriUtils.decode(filepath, "UTF-8");
        } catch (Exception e1) {
            // TODO Auto-generated catch block
            logger.error(String.format("解释文件路径失败，URL地址为%s", filepath), e1);
        }
        if ("pdf".equalsIgnoreCase(sysFile.getFileType())) {
            return coverMessage("200","success",filepath);
        }else {
            return coverMessage("500","格式错误");
        }
    }
    @RequestMapping("/devDoc")
    @ResponseBody
    public void devDoc(HttpServletRequest request, HttpServletResponse response, String id) throws Exception {
        request.setCharacterEncoding("UTF-8");
        String ctxPath = request.getSession().getServletContext().getRealPath("");
        SysFile sysFile = fileservice.getById(id);
        String encode = URLEncoder.encode(sysFile.getFilename(), "UTF-8");
        if (sysFile == null) {
            throw new Exception(" current request path is empty");
        }
        String filepath = sysFile.getUrl();
        int index = filepath.lastIndexOf(Global.USER_DIR);
        if (index >= 0) {
            filepath = filepath.substring(index + Global.USER_DIR.length());

        }
        try {
            filepath = UriUtils.decode(filepath, "UTF-8");
        } catch (Exception e1) {
            // TODO Auto-generated catch block
            logger.error(String.format("解释文件路径失败，URL地址为%s", filepath), e1);
        }
        File file = new File(Global.getUploadBaseDir() + filepath);
        response.setContentType("application/pdf");
        FileInputStream in = new FileInputStream(file);
        OutputStream out = response.getOutputStream();
        byte[] b = new byte[512];
        while ((in.read(b))!=-1) {
            out.write(b);
        }
        out.flush();
        in.close();
        out.close();
    }
}
